package com.farm.wda.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import com.farm.wda.Beanfactory;

public class HtmlUtils {

	/**
	 * 下载网络资源
	 * 
	 * @param eurl
	 *            资源地址
	 * @return fileid
	 * @throws IOException
	 */
	public static File downloadWebFile(String key, String eurl, String filename) throws IOException {
		String exname = null;
		try {
			if (eurl.lastIndexOf("?") > 0) {
				exname = eurl.substring(0, eurl.lastIndexOf("?"));
			} else {
				exname = eurl;
			}
			if (exname.lastIndexOf(".") > 0) {
				exname = exname.substring(exname.lastIndexOf(".") + 1);
			} else {
				exname = eurl;
			}
			if (exname == null || exname.length() > 10) {
				exname = "gif";
			}
		} catch (Exception e) {
			exname = "gif";
		}
		try {
			SSRFConnectionHandles.validateUrl(eurl);
			URL innerurl = new URL(eurl);
			// 创建连接的地址
			HttpURLConnection connection = (HttpURLConnection) innerurl.openConnection();
			// 返回Http的响应状态码
			InputStream input = null;
			try {
				input = connection.getInputStream();
			} catch (Exception e) {
				throw new RuntimeException("文件无法访问："+eurl);
			}
			File file = new File(Beanfactory.WEB_DIR + File.separator+Beanfactory.getFileKeyCoderImpl().parseDir(key) + File.separator + filename);
			file.getParentFile().mkdirs();
			OutputStream fos = new FileOutputStream(file);
			// 获取输入流
			try {
				int bytesRead = 0;
				byte[] buffer = new byte[8192];
				while ((bytesRead = input.read(buffer, 0, 8192)) != -1) {
					fos.write(buffer, 0, bytesRead);
				}
			} finally {
				input.close();
				fos.close();
			}
			return file;
			// config.file.client.html.resource.url
		} catch (IOException e) {
			e = new IOException(SSRFConnectionHandles.exceptionHandle(e));
			throw e;
		}
	}

}
